package com.itheima.common.fegin;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author qiankaofei
 * @version 1.0
 * @date 2020/11/17 9:19
 *  该配置类作用:
 *      fegin配置类，解决在远程调用过程中请求头转发丢失问题
 */
@Configuration
public class feignConfiguration {
    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //获取RequestContextHolder域对象
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if(attributes!=null){
                    HttpServletRequest request = attributes.getRequest();
                    Enumeration<String> headerNames = request.getHeaderNames();
                    if(headerNames!=null){
                        //将老的请求头中的数据添加到转发是创建的新的Request对象中
                        while (headerNames.hasMoreElements()) {
                            String name = headerNames.nextElement();
                            String value = request.getHeader(name);
                            template.header(name,value);
                        }
                    }
                }
            }
        };
    }
}
